from django.http import HttpResponse
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from threading import Thread
import re
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms_code.tasks import send_sms_code
from users.models import User
# Create your views here.

# def send_sms_code(mobile, sms_code):
#     # 发送短信
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code, '5'], 1)
from users.serializers import UserSerializers
from meiduo_mall.libs.captcha.captcha import captcha


class SMS_Code_View(APIView):
    def get(self, request, mobile):
        # 获取前端传递的手机号
        # 验证手机号格式
        # 链接redis数据库
        conn = get_redis_connection('sms_code')
        # 判断前端的请求的时间间隔是否在60s内
        flag = conn.get('sms_code_flag_%s'%mobile)
        if flag:
            return Response({'error':'请求频繁不可取'}, status = 403)
        # 生成短信验证码
        sms_code = "%06d"%randint(0,999999)
        # 创建管道
        pl = conn.pipeline()
        # 保存短信  redis
        pl.setex('sms_code_%s'%mobile, 300, sms_code)
        # 写入一个标志数据，验证是否在60s内有相同手机号进行请求
        pl.setex('sms_code_flag_%s'%mobile, 60, 111)
        # 将指令通过管道传递给redis数据库
        pl.execute()
        # 发送短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '5'], 1)
        # print(mobile)
        # t_ccp_send = Thread(target= send_sms_code, kwargs = {'mobile':mobile, 'sms_code':sms_code})
        # t_ccp_send.start()

        # 使用celery
        send_sms_code.delay(mobile, sms_code)
        # 结果返回
        return Response('ok')


# 判断用户名是否重复
class UserNameView(APIView):

    def get(self, request, username):
        count = User.objects.filter(username = username).count()

        return Response( {'count':count} )


class MobileView(APIView):

    def get(self, request, mobile):
        count = User.objects.filter(mobile = mobile).count()

        return Response( {'count':count} )

# 注册用户
class UserView(CreateAPIView):

    serializer_class = UserSerializers


Image_datas = 'aasfdsgfsfsad'


class Image_data(CreateAPIView):
    # 返回图形验证码
    def get(self, request):
        print(111)
        global Image_datas
        name, text, image_data = captcha.generate_captcha()
        Image_datas = text

        return HttpResponse(image_data,'image/jpg')


Mobile = None


class Find_Mobile(APIView):

    def get(self,request,mobile=None,token=None):
        print(222)
        print(Image_datas)

        flag = re.match(r'^1[3-9]\d{9}',mobile)
        global Mobile
        Mobile = mobile
        text = request.query_params.get('text')
        print(text)
        if text is not None:
            if Image_datas.lower() != text.lower():
                return Response(status=400)
            if flag:
                return Response({'mobile':mobile, 'token':token}, status=200)
            else:
                return Response(status=404)
        print("444444========")
        if not text:
            return Response('ok')


class Send_SMS_Code(APIView):
    def get(self, request):
        # 获取前端传递的手机号
        # 验证手机号格式
        # 链接redis数据库
        conn = get_redis_connection('sms_code')
        # 判断前端的请求的时间间隔是否在60s内
        flag = conn.get('sms_code_flag_%s'%Mobile)
        if flag:
            return Response({'error':'请求频繁不可取'}, status = 403)
        # 生成短信验证码
        sms_code = "%06d"%randint(0,999999)
        # 创建管道
        pl = conn.pipeline()
        # 保存短信  redis
        pl.setex('sms_code_%s'%Mobile, 300, sms_code)
        # 写入一个标志数据，验证是否在60s内有相同手机号进行请求
        pl.setex('sms_code_flag_%s'%Mobile, 60, 111)
        # 将指令通过管道传递给redis数据库
        pl.execute()
        # 发送短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '5'], 1)
        # print(mobile)
        # t_ccp_send = Thread(target= send_sms_code, kwargs = {'mobile':mobile, 'sms_code':sms_code})
        # t_ccp_send.start()

        # 使用celery
        send_sms_code.delay(Mobile, sms_code)
        # 结果返回
        return Response('ok')


class Find_Password(APIView):
    def get(self,request):

















